import { useEffect, useMemo, useState } from 'react';
import Picker, { PickerProps } from '../Picker/index';
import { OptionItem, TimeRange } from '../Picker/type';
import { getDateByTimeRange, useOptionsByTimeRange } from '../Picker/utils';
import { useReactive } from 'ahooks';
import dayjs from 'dayjs';

interface TimePickerProps extends Omit<PickerProps, 'options' | 'value' | 'onChange' | 'mode' | 'joinValues'> {
  /** 选择范围 默认day年月日, year年, month年月, day-time年月日时分秒, day-time-minute年月日时分, time时分秒, hour-minute时分, hour小时, minute分, minute-second分秒, second秒 */
  timeRange?: TimeRange;
  value?: string;
  onChange?: (value: TimePickerProps['value']) => any;

  /** value转化格式，默认值根据timeRange变化 */
  valueFormat?: string;
}

const defaultFormats = {
  year: 'YYYY',
  month: 'YYYY-MM',
  day: 'YYYY-MM-DD',
  'day-time': 'YYYY-MM-DD HH:mm:ss',
  time: 'HH:mm:ss',
  'day-time-minute': 'YYYY-MM-DD HH:mm',
  'hour-minute': 'HH:mm',
  hour: 'HH',
  minute: 'mm',
  'minute-second': 'mm:ss',
  second: 'ss',
};

const TimePicker = (props: TimePickerProps) => {
  const { value, onChange, timeRange = 'day' } = props;
  const [date, setDate] = useState(value || '');
  const valueFormat = props.valueFormat || defaultFormats[timeRange];
  const { options, defaultSelectedValue } = useOptionsByTimeRange(timeRange, date);

  useEffect(() => {
    if (value) {
      setDate(value!);
    }
  }, [value]);

  const staticStr = useMemo(() => {
    if (!value) return '';
    return value;
  }, [value]);

  // console.log('TimePicker', { staticStr, timeRange, options, defaultSelectedValue });
  return (
    <Picker
      {...props}
      mode='multiSelector'
      options={options}
      onChange={v => {
        const val = v as string[];
        const date1 = !val?.length ? '' : getDateByTimeRange(timeRange, val);
        console.log('TimePicker onChange ', { val, date1 }, dayjs(date1).format(valueFormat));
        if (!date1) {
          onChange?.('');
          return;
        }
        onChange?.(dayjs(date1).format(valueFormat));
      }}
      value={defaultSelectedValue as string[]}
      isUseParentStatic
      staticStr={staticStr}
      joinValues={false}
      onColumnChange={e => {
        console.log('TimePicker onColumnChange e', e);
        const val = e.detail.value as string[];
        const date1 = !val?.length ? '' : getDateByTimeRange(timeRange, val);
        console.log('date1', date1);
        setDate(date1!);
      }}
    />
  );
};
export default TimePicker;
